package com.lxb.myforum.service

import java.util.Date

import com.lxb.myforum.base.BaseService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.domain.Page
import org.springframework.data.domain.Pageable
import org.springframework.stereotype.Service

import com.lxb.myforum.pojo.Article
import com.lxb.myforum.repository.ArticleRepository
import com.lxb.myforum.service.spec.ArticleSpec

@Service
class ArticleService @Autowired
constructor(private val articleRepository: ArticleRepository) : BaseService() {

    fun count(): Long {
        return articleRepository.count()
    }

    fun count(article: Article): Long {
        return articleRepository.count(ArticleSpec(article))
    }

    fun findById(id: Long): Article {
        return articleRepository.findById(id).orElseThrow {
            RuntimeException("不存在id为 $id 的model")
        }
    }

    fun findArticles(article: Article, pageable: Pageable): Page<Article> {
        return articleRepository.findAll(ArticleSpec(article), pageable)
    }


    /**
     * 保存文章 （新增或者更新）
     * @param article 需要保存的article[Article]
     * @return
     */
    fun saveArticle(article: Article): Article {
        if (article.id == null) {
            article.createTime = Date()
        }
        article.updateTime = Date() // 更新时间一直在变的
        return articleRepository.save(article)
    }
}
